import http from './request'
import { 
  API_CONFIG, 
  WORKSHEET_IDS, 
  VIEW_IDS, 
  SUPPLIER_FIELDS,
  PRODUCT_FIELDS,
  ORDER_FIELDS,
  QUANTITY_FIELDS,
  LOCATION_FIELDS,
  LOCATION_STOCK_FIELDS,
  CONTAINER_FIELDS,
  EXCLUDED_LOCATIONS,
  transformPickingOrderData,
  FILTER_TYPES,
  DATA_TYPES,
  PAGINATION_CONFIG,
  getConfigSnapshot
} from '../config/wms-config.js'

class WMSApiService {
  constructor() {
    if (WMSApiService.instance) {
      return WMSApiService.instance
    }
    
    // 认证和ID不在构造时固化，改为请求时取（避免 mdye 尚未注入）
    Object.defineProperties(this, {
      appKey: { get: () => API_CONFIG.appKey },
      sign: { get: () => API_CONFIG.sign },
      secretKey: { get: () => API_CONFIG.secretKey },
      worksheetId: { get: () => WORKSHEET_IDS.PICKING_ORDERS },
      viewId: { get: () => VIEW_IDS.PICKING_ORDERS_DEFAULT }
    })
    
    WMSApiService.instance = this
  }

  // 基础API请求方法
  async makeRequest(endpoint, params = {}) {
    try {
      // 调试：输出 mdye.env.config 的可用键，帮助定位参数ID不匹配
      const tryRead = (w) => {
        if (!w) return null
        if (w.mdye && w.mdye.env && w.mdye.env.config) return w.mdye.env.config
        if (w.mdye && w.mdye.env) return w.mdye.env
        if (w.env) return w.env
        return null
      }
      let mdyeCfg = null
      if (typeof window !== 'undefined') {
        const candidates = [window, window.parent, window.top]
        for (const c of candidates) {
          mdyeCfg = tryRead(c)
          if (mdyeCfg) break
        }
      }
      if (mdyeCfg && !this._mdyeKeysPrinted) {
        try {
          console.log('[mdye.env.config keys]:', Object.keys(mdyeCfg))
          console.log('[config snapshot]:', getConfigSnapshot())
        } catch (e) {}
        this._mdyeKeysPrinted = true
      } else if (!mdyeCfg && !this._mdyeKeysPrinted) {
        console.warn('[mdye.env.config] 不可用，可能尚未注入或变量未配置')
        this._mdyeKeysPrinted = true
      }

      const requestData = {
        appKey: this.appKey,
        sign: this.sign,
        worksheetId: params.worksheetId || this.worksheetId, // 允许覆盖工作表ID
        notGetTotal: false,
        pageSize: PAGINATION_CONFIG.DEFAULT_PAGE_SIZE,
        pageIndex: 1,
        ...params
      }

      // 必填项校验，提示具体缺少的变量ID
      const missing = []
      if (!requestData.appKey) missing.push('AppKey')
      if (!requestData.sign) missing.push('Sign')
      if (!requestData.worksheetId) missing.push('JHworksheetId 或调用参数中的 worksheetId')
      if (missing.length) {
        console.error('请求缺少必要参数:', missing)
        console.error('字段映射检查: ', {
          SUPPLIER_FIELDS: SUPPLIER_FIELDS,
          PRODUCT_FIELDS: PRODUCT_FIELDS,
          ORDER_FIELDS: ORDER_FIELDS,
          QUANTITY_FIELDS: QUANTITY_FIELDS,
          LOCATION_FIELDS: LOCATION_FIELDS,
          LOCATION_STOCK_FIELDS: LOCATION_STOCK_FIELDS,
          CONTAINER_FIELDS: CONTAINER_FIELDS
        })
        if (mdyeCfg) {
          console.log('当前 mdye.env.config 已配置键:', Object.keys(mdyeCfg))
        }
      }
      
      // 只有当viewId存在且不为undefined时才添加
      const viewId = params.viewId !== undefined ? params.viewId : this.viewId;
      if (viewId) {
        requestData.viewId = viewId;
      }

      // 特殊处理filters参数 - 明道云API需要JSON字符串格式
      if (requestData.filters && Array.isArray(requestData.filters)) {
        if (requestData.filters.length > 0) {
          requestData.filters = JSON.stringify(requestData.filters)
        } else {
          // 空数组时删除filters参数
          delete requestData.filters
        }
      }

      console.log(`API请求 ${endpoint}:`, requestData)
      console.log('API基础地址:', http.defaults.baseURL || '(由拦截器动态注入)')
      console.log(`API请求URL(相对): /${endpoint}`)
      
      const response = await http.post(`/${endpoint}`, requestData)
      console.log(`API响应 ${endpoint}:`, response)
      
      return response
    } catch (error) {
      console.error(`API请求失败 ${endpoint}:`, error)
      throw error
    }
  }

  // 获取所有拣货单数据（用于提取供应商信息）
  async getAllPickingOrders() {
    try {
      console.log('开始获取拣货单数据...')
      const response = await this.makeRequest('getFilterRows', {
        filters: []
      })
      
      console.log('API响应原始数据:', response)
      console.log('response所有属性:', Object.keys(response))
      console.log('response.rows存在?', !!response.rows)
      console.log('response.data存在?', !!response.data)
      
      // 检查不同可能的数据结构
      let actualRows = null;
      if (response.rows) {
        actualRows = response.rows;
        console.log('找到数据在 response.rows');
      } else if (response.data && response.data.rows) {
        actualRows = response.data.rows;
        console.log('找到数据在 response.data.rows');
      } else if (response.data && Array.isArray(response.data)) {
        actualRows = response.data;
        console.log('找到数据在 response.data (数组格式)', response.data);
      } else {
        console.log('未找到rows数据，完整响应结构:', JSON.stringify(response, null, 2));
      }
      
      
      if (actualRows && Array.isArray(actualRows)) {
        console.log('找到有效数据，长度:', actualRows.length);
        console.log('准备调用数据转换函数...')
        // 使用配置文件中的数据转换函数
        const transformedData = transformPickingOrderData(actualRows)
        console.log('转换后的拣货单数据:', transformedData)
        return {
          ...response,
          rows: transformedData
        }
      }
      
      console.warn('API响应中没有找到有效的rows数据')
      return response
    } catch (error) {
      console.error('获取拣货单数据失败:', error)
      throw error
    }
  }

  // 为了保持向后兼容，保留getSuppliers方法
  async getSuppliers() {
    return this.getAllPickingOrders()
  }

  // 根据供应商名称获取拣货单
  async getPickingOrders(supplierName) {
    try {
      const filters = []
      
      if (supplierName && supplierName.trim()) {
        filters.push({
          controlId: SUPPLIER_FIELDS.NAME,
          value: supplierName.trim(),
          dataType: DATA_TYPES.TEXT,
          spliceType: FILTER_TYPES.EQUAL
        })
      }
      
      const response = await this.makeRequest('getFilterRows', {
        filters: filters
      })
      
      // 使用相同的数据结构检查逻辑
      let actualRows = null;
      if (response.rows) {
        actualRows = response.rows;
      } else if (response.data && response.data.rows) {
        actualRows = response.data.rows;
      } else if (response.data && Array.isArray(response.data)) {
        actualRows = response.data;
      }
      
      if (actualRows && Array.isArray(actualRows)) {
        // 使用配置文件中的数据转换函数
        const transformedData = transformPickingOrderData(actualRows)
        console.log(`供应商 ${supplierName} 的拣货单数据:`, transformedData)
        return {
          ...response,
          rows: transformedData
        }
      }
      
      return response
    } catch (error) {
      console.error('获取拣货单失败:', error)
      throw error
    }
  }

  // 获取拣货详情
  async getPickingDetails(orderId) {
    try {
      const response = await http.post('/getRowById', {
        appKey: this.appKey,
        sign: this.sign,
        worksheetId: this.worksheetId,
        rowId: orderId,
        getSystemControl: false
      })
      
      if (response && response.controls) {
        // 使用配置文件中的数据转换函数
        const mockRow = {
          rowid: orderId,
          controls: response.controls
        }
        const transformedData = transformPickingOrderData([mockRow])
        return transformedData.length > 0 ? transformedData[0] : null
      }
      
      return response
    } catch (error) {
      console.error('获取拣货详情失败:', error)
      throw error
    }
  }

  // 更新拣货状态
  async updatePickingStatus(orderId, status, phoneNumber) {
    try {
      // 这里可能需要根据实际业务需求调整
      // 可能是更新原有记录而不是新增记录
      const response = await http.post('/editRow', {
        appKey: this.appKey,
        sign: this.sign,
        worksheetId: this.worksheetId,
        rowId: orderId,
        controls: [
          {
            controlId: QUANTITY_FIELDS.STATUS, // 状态字段
            value: status
          }
        ]
      })
      return response
    } catch (error) {
      console.error('更新拣货状态失败:', error)
      throw error
    }
  }

  // 更新拣货单的容器码
  async updatePickingOrderContainerCode(orderId, containerCode) {
    try {
      console.log('开始更新拣货单容器码:', {
        orderId,
        containerCode,
        containerCodeFieldId: QUANTITY_FIELDS.CONTAINER_CODE
      })
      
      const response = await http.post('/editRow', {
        appKey: this.appKey,
        sign: this.sign,
        worksheetId: this.worksheetId,
        rowId: orderId,
        controls: [
          {
            controlId: QUANTITY_FIELDS.CONTAINER_CODE, // 拣货单中的容器码字段
            value: containerCode
          }
        ]
      })
      
      console.log('更新拣货单容器码成功:', response)
      return response
    } catch (error) {
      console.error('更新拣货单容器码失败:', error)
      throw error
    }
  }

  // 提交拣货
  async submitPicking(orderId, pickedQuantity, phoneNumber) {
    try {
      // 更新已拣货数量
      const response = await http.post('/editRow', {
        appKey: this.appKey,
        sign: this.sign,
        worksheetId: this.worksheetId,
        rowId: orderId,
        controls: [
          {
            controlId: QUANTITY_FIELDS.PICKED, // 已拣货数字段
            value: pickedQuantity
          }
        ]
      })
      return response
    } catch (error) {
      console.error('提交拣货失败:', error)
      throw error
    }
  }

  // 获取当前用户信息（外部门户操作者）
  async getCurrentUserInfo() {
    try {
      console.log('开始获取外部门户当前用户信息...')
      
      // 从全局config对象获取外部门户用户信息
      const config = window.config || window.mdAppConfig || {};
      console.log('外部门户config对象:', config);
      
      if (config && config.currentAccount) {
        const userInfo = {
          phone: config.currentAccount.mobilePhone || config.currentAccount.phone || '',
          name: config.currentAccount.fullName || config.currentAccount.name || config.currentAccount.userName || '',
          userId: config.currentAccount.accountId || config.currentAccount.id || '',
          email: config.currentAccount.email || '',
          avatar: config.currentAccount.avatar || ''
        };
        
        console.log('外部门户用户信息:', userInfo);
        return userInfo;
      }
      
      console.warn('无法获取外部门户用户信息，config.currentAccount不存在');
      
    } catch (error) {
      console.error('获取外部门户用户信息失败:', error);
    }
    
    // 如果获取用户信息失败，返回默认值
    console.warn('使用默认用户信息');
    return {
      phone: '13800138000', // 默认手机号
      name: '系统操作员', // 默认姓名
      userId: 'default_user'
    };
  }
  // 发送webhook到明道云工作流（去拣货操作）
  async sendWebhook(data) {
    try {
      console.log('准备发送webhook到:', API_CONFIG.webhookURL)
      console.log('webhook数据:', data)
      
      // 直接向webhook URL发送POST请求
      const response = await fetch(API_CONFIG.webhookURL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
      
      const result = await response.text()
      console.log('Webhook响应:', result)
      
      if (response.ok) {
        console.log('Webhook发送成功')
        return { success: true, data: result }
      } else {
        throw new Error(`Webhook请求失败: ${response.status} ${response.statusText}`)
      }
    } catch (error) {
      console.error('发送webhook失败:', error)
      // webhook失败不应该影响主要业务流程
      console.warn('Webhook发送失败，但继续处理业务逻辑')
      return { success: false, error: error.message }
    }
  }

  // 发送提交拣货webhook到明道云工作流
  async sendSubmitWebhook(data) {
    try {
      console.log('准备发送提交拣货webhook到:', API_CONFIG.submitWebhookURL)
      if (!API_CONFIG.submitWebhookURL) {
        console.warn('submitWebhookURL 为空，请在插件参数中配置 submitWebhookURL 或 completeWebhook')
      }
      console.log('提交拣货webhook数据:', data)
      
      // 直接向提交拣货webhook URL发送POST请求
      const response = await fetch(API_CONFIG.submitWebhookURL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
      
      const result = await response.text()
      console.log('提交拣货Webhook响应:', result)
      
      if (response.ok) {
        console.log('提交拣货Webhook发送成功')
        return { success: true, data: result }
      } else {
        throw new Error(`提交拣货Webhook请求失败: ${response.status} ${response.statusText}`)
      }
    } catch (error) {
      console.error('发送提交拣货webhook失败:', error)
      // webhook失败不应该影响主要业务流程
      console.warn('提交拣货Webhook发送失败，但继续处理业务逻辑')
      return { success: false, error: error.message }
    }
  }

  // 发送拣货完成webhook到明道云工作流
  async sendCompleteWebhook(data) {
    try {
      console.log('准备发送绑定容器/完成类 webhook 到:', API_CONFIG.completeWebhookURL)
      if (!API_CONFIG.completeWebhookURL) {
        console.warn('completeWebhookURL 为空，请在插件参数中配置 completeWebhookURL 或 rqWebhook')
      }
      console.log('拣货完成webhook数据:', data)
      
      // 直接向拣货完成webhook URL发送POST请求
      const response = await fetch(API_CONFIG.completeWebhookURL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
      
      const result = await response.text()
      console.log('拣货完成Webhook响应:', result)
      
      if (response.ok) {
        console.log('拣货完成Webhook发送成功')
        return { success: true, data: result }
      } else {
        throw new Error(`拣货完成Webhook请求失败: ${response.status} ${response.statusText}`)
      }
    } catch (error) {
      console.error('发送拣货完成webhook失败:', error)
      // webhook失败不应该影响主要业务流程
      console.warn('拣货完成Webhook发送失败，但继续处理业务逻辑')
      return { success: false, error: error.message }
    }
  }

  // 配置验证方法
  validateConfiguration() {
    const issues = []
    
    if (!this.appKey) issues.push('缺少AppKey')
    if (!this.sign) issues.push('缺少Sign')
    if (!this.worksheetId) issues.push('缺少WorksheetId')
    if (!this.viewId) issues.push('缺少ViewId')
    if (!SUPPLIER_FIELDS.NAME) issues.push('缺少供应商名称字段ID')
    
    console.log('配置验证结果:', {
      appKey: this.appKey ? '已设置' : '未设置',
      sign: this.sign ? '已设置' : '未设置', 
      worksheetId: this.worksheetId,
      viewId: this.viewId,
      supplierField: SUPPLIER_FIELDS.NAME
    })
    
    return {
      isValid: issues.length === 0,
      issues
    }
  }

  // 测试基础连接的方法
  async testConnection() {
    try {
      console.log('开始测试明道云连接...')
      console.log('使用配置:', {
        appKey: this.appKey,
        worksheetId: this.worksheetId,
        viewId: this.viewId
      })
      
      const response = await this.makeRequest('getFilterRows', {
        pageSize: 1  // 只获取1条记录用于测试
      })
      
      console.log('连接测试成功:', response)
      return {
        success: true,
        data: response
      }
    } catch (error) {
      console.error('连接测试失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 测试webhook连接
  async testWebhook() {
    try {
      console.log('开始测试webhook连接...')
      
      // 获取外部门户用户信息进行测试
      const userInfo = await this.getCurrentUserInfo()
      
      const testData = {
        // 外部门户标准字段
        rowid: 'test_order',
        accountId: userInfo.phone,
        
        // 测试数据
        action: 'test_connection',
        operatorPhone: userInfo.phone,
        operatorName: userInfo.name,
        operatorUserId: userInfo.userId,
        orderId: 'test_order',
        productName: '测试商品',
        supplierName: '测试供应商',
        timestamp: new Date().toISOString(),
        message: '这是一个外部门户webhook连接测试'
      }
      
      const result = await this.sendWebhook(testData)
      console.log('Webhook测试结果:', result)
      return result
    } catch (error) {
      console.error('Webhook测试失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 测试提交拣货webhook连接
  async testSubmitWebhook() {
    try {
      console.log('开始测试提交拣货webhook连接...')
      const testData = {
        action: 'test_submit_picking',
        operatorPhone: '13800138000',
        operatorName: '测试用户',
        operatorUserId: 'test_user',
        orderId: 'test_order_001',
        productName: '测试商品',
        supplierName: '测试供应商',
        batchCode: 'TEST20240101',
        barcode: '1234567890123',
        productionDate: '2024-01-01',
        quantity: 10,
        requiredQuantity: 50,
        pickedQuantity: 10,
        remainingQuantity: 40,
        timestamp: new Date().toISOString(),
        message: '这是一个提交拣货webhook连接测试'
      }
      
      const result = await this.sendSubmitWebhook(testData)
      console.log('提交拣货Webhook测试结果:', result)
      return result
    } catch (error) {
      console.error('提交拣货Webhook测试失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 测试库位库存API配置
  async testLocationStockAPI() {
    try {
      console.log('开始测试库位库存API配置...')
      
      // 测试基础连接（不带筛选条件）
      const basicTest = await http.post('/getFilterRows', {
        appKey: this.appKey,
        sign: this.sign,
        worksheetId: WORKSHEET_IDS.LOCATION_STOCK,
        notGetTotal: false,
        pageSize: 5,
        pageIndex: 1
        // 不传递filters参数，避免转换问题
      })
      
      console.log('库位库存API基础测试响应:', basicTest)
      
      const testResult = {
        测试时间: new Date().toLocaleString(),
        API配置: {
          工作表ID: WORKSHEET_IDS.LOCATION_STOCK,
          AppKey: this.appKey ? '已配置' : '未配置',
          Sign: this.sign ? '已配置' : '未配置'
        },
        字段配置: {
          库位编码字段ID: LOCATION_STOCK_FIELDS.LOCATION_CODE,
          商品名称字段ID: LOCATION_STOCK_FIELDS.PRODUCT_NAME,
          供应商名称字段ID: LOCATION_STOCK_FIELDS.SUPPLIER_NAME,
          生产日期字段ID: LOCATION_STOCK_FIELDS.PRODUCTION_DATE,
          锁定库存字段ID: LOCATION_STOCK_FIELDS.LOCKED_STOCK
        }
      }
      
      // 检查响应数据结构
      if (basicTest) {
        testResult.API响应结构 = Object.keys(basicTest)
        
        let actualRows = null;
        if (basicTest.rows) {
          actualRows = basicTest.rows;
        } else if (basicTest.data && basicTest.data.rows) {
          actualRows = basicTest.data.rows;
        } else if (basicTest.data && Array.isArray(basicTest.data)) {
          actualRows = basicTest.data;
        }
        
        if (actualRows && Array.isArray(actualRows)) {
          testResult.数据状态 = {
            找到记录数: actualRows.length,
            数据格式: '正常'
          }
          
          if (actualRows.length > 0) {
            const firstRow = actualRows[0]
            testResult.数据样本 = {
              记录ID: firstRow.rowid || '无',
              所有字段: Object.keys(firstRow),
              库位编码值: firstRow[LOCATION_STOCK_FIELDS.LOCATION_CODE] || '字段ID不匹配或无数据',
              商品名称值: firstRow[LOCATION_STOCK_FIELDS.PRODUCT_NAME] || '字段ID不匹配或无数据',
              供应商名称值: firstRow[LOCATION_STOCK_FIELDS.SUPPLIER_NAME] || '字段ID不匹配或无数据',
              生产日期值: firstRow[LOCATION_STOCK_FIELDS.PRODUCTION_DATE] || '字段ID不匹配或无数据',
              锁定库存值: firstRow[LOCATION_STOCK_FIELDS.LOCKED_STOCK] || '字段ID不匹配或无数据'
            }
          }
        } else {
          testResult.数据状态 = {
            找到记录数: 0,
            数据格式: '异常',
            响应详情: basicTest
          }
        }
      } else {
        testResult.API响应状态 = '无响应或响应为空'
      }
      
      return testResult
      
    } catch (error) {
      console.error('库位库存API测试失败:', error)
      return {
        测试状态: '失败',
        错误信息: error.message,
        错误详情: error
      }
    }
  }

  // 获取库位库存数据（根据商品、供应商和生产日期筛选）
  async getLocationStock(productName, supplierName, productionDate = null, pickingType = null) {
    try {
      console.log(`开始获取库位库存数据 - 商品: ${productName}, 供应商: ${supplierName}, 生产日期: ${productionDate}, 拣货类型: ${pickingType}`)
      
      // 第一步：先测试基础连接（不带筛选条件）
      console.log('第一步：测试库位库存表基础连接...')
      const basicResponse = await http.post('/getFilterRows', {
        appKey: this.appKey,
        sign: this.sign,
        worksheetId: WORKSHEET_IDS.LOCATION_STOCK,
        notGetTotal: false,
        pageSize: 10,
        pageIndex: 1
      })
      
      console.log('库位库存表基础连接响应:', basicResponse)
      
      // 检查基础响应是否成功
      if (!basicResponse || (!basicResponse.rows && !basicResponse.data)) {
        throw new Error('无法连接到库位库存表或表中无数据')
      }
      
      // 如果基础连接成功，返回所有数据进行前端筛选
      // 暂时不在API层面进行筛选，避免filters参数问题
      const response = basicResponse
      
      console.log('库位库存API响应:', response)
      console.log('库位库存筛选条件:', {
        商品名称: productName,
        供应商名称: supplierName,
        生产日期: productionDate,
        拣货类型: pickingType,
        筛选方式: '前端筛选',
        特殊规则: pickingType === '残品出库' ? '只显示CP-01-01-01-01库位' : '排除特殊库位'
      })
      
      // 处理响应数据
      let actualRows = null;
      if (response.rows) {
        actualRows = response.rows;
      } else if (response.data && response.data.rows) {
        actualRows = response.data.rows;
      } else if (response.data && Array.isArray(response.data)) {
        actualRows = response.data;
      }
      
      if (actualRows && Array.isArray(actualRows)) {
        // 转换和过滤库位数据
        const filteredLocations = actualRows
          .map(row => {
            // 规范化处理库位编码，支持英文字母、数字、特殊字符
            const rawLocationCode = LOCATION_STOCK_FIELDS.LOCATION_CODE ? 
              (row[LOCATION_STOCK_FIELDS.LOCATION_CODE] || '') : 
              `位置-${row.rowid || 'unknown'}`;
            const locationCode = typeof rawLocationCode === 'string' ? 
              rawLocationCode.trim().replace(/\s+/g, ' ') : rawLocationCode;
            
            return {
              id: row.rowid || '',
              locationCode: locationCode,
              productName: row[LOCATION_STOCK_FIELDS.PRODUCT_NAME] || '',
              supplierName: row[LOCATION_STOCK_FIELDS.SUPPLIER_NAME] || '',
              productionDate: row[LOCATION_STOCK_FIELDS.PRODUCTION_DATE] || '',
              stockQuantity: parseInt(row[LOCATION_STOCK_FIELDS.STOCK_QUANTITY] || '0'),
              lockedStock: parseInt(row[LOCATION_STOCK_FIELDS.LOCKED_STOCK] || '0'),
              rawData: row
            }
          })
          .filter(location => {
            // 前端筛选：商品名称匹配
            if (productName && productName.trim()) {
              const cleanProductName = productName.trim().replace(/\s+/g, ' ');
              const locationProductName = (location.productName || '').trim().replace(/\s+/g, ' ');
              if (locationProductName !== cleanProductName) {
                return false;
              }
            }
            
            // 前端筛选：供应商名称匹配
            if (supplierName && supplierName.trim()) {
              const cleanSupplierName = supplierName.trim().replace(/\s+/g, ' ');
              const locationSupplierName = (location.supplierName || '').trim().replace(/\s+/g, ' ');
              if (locationSupplierName !== cleanSupplierName) {
                return false;
              }
            }
            
            // 前端筛选：生产日期匹配
            if (productionDate && productionDate.trim()) {
              const cleanProductionDate = productionDate.trim().replace(/\s+/g, ' ');
              const locationProductionDate = (location.productionDate || '').trim().replace(/\s+/g, ' ');
              if (locationProductionDate !== cleanProductionDate) {
                return false;
              }
            }
            
            // 特殊拣货类型的库位过滤逻辑
            if (pickingType === '残品出库') {
              // 残品出库只能选择CP-01-01-01-01库位
              if (location.locationCode !== 'CP-01-01-01-01') {
                return false;
              }
            } else {
              // 非残品出库排除指定的库位编码（包括CP-01-01-01-01）
              if (LOCATION_STOCK_FIELDS.LOCATION_CODE && EXCLUDED_LOCATIONS.includes(location.locationCode)) {
                return false;
              }
            }
            
            // 只显示锁定库存大于0的库位
            return location.lockedStock > 0;
          })
        
        console.log('过滤后的库位库存数据:', filteredLocations)
        
        return {
          ...response,
          rows: filteredLocations
        }
      }
      
      return { ...response, rows: [] }
      
    } catch (error) {
      console.error('获取库位库存数据失败:', error)
      throw error
    }
  }

  // 获取可用容器数据（获取全部容器，前端筛选）
  async getAvailableContainers(orderDeliveryStation = '') {
    try {
      console.log('=== 开始获取容器数据 ===')
      console.log('容器管理表工作表ID:', WORKSHEET_IDS.CONTAINER_MANAGEMENT)
      console.log('容器码字段ID:', CONTAINER_FIELDS.CONTAINER_CODE)
      console.log('容器状态字段ID:', CONTAINER_FIELDS.STATUS)
      console.log('容器配送站点字段ID:', CONTAINER_FIELDS.DELIVERY_STATION)
      console.log('订单配送站点:', orderDeliveryStation)
      
      // 尝试多种方式获取数据
      let response = null
      
      // 方式1：标准API调用，大页面
      console.log('尝试方式1: 标准API调用，大页面')
      try {
        response = await this.makeRequest('getFilterRows', {
          worksheetId: WORKSHEET_IDS.CONTAINER_MANAGEMENT,
          pageSize: 200,
          pageIndex: 1,
          notGetTotal: false
        })
        console.log('方式1结果:', response?.rows?.length || 0, '条记录')
      } catch (error) {
        console.log('方式1失败:', error.message)
      }
      
      // 方式2：如果方式1没数据，尝试不带任何可选参数
      if (!response?.rows?.length) {
        console.log('尝试方式2: 最简参数')
        try {
          response = await http.post('/getFilterRows', {
            appKey: this.appKey,
            sign: this.sign,
            worksheetId: WORKSHEET_IDS.CONTAINER_MANAGEMENT
          })
          console.log('方式2结果:', response?.rows?.length || 0, '条记录')
        } catch (error) {
          console.log('方式2失败:', error.message)
        }
      }
      
      // 方式3：如果还是没数据，尝试直接API调用而不通过makeRequest
      if (!response?.rows?.length) {
        console.log('尝试方式3: 直接API调用')
        try {
          response = await http.post('/getFilterRows', {
            appKey: this.appKey,
            sign: this.sign,
            worksheetId: WORKSHEET_IDS.CONTAINER_MANAGEMENT,
            pageSize: 100,
            pageIndex: 1,
            notGetTotal: true
          })
          console.log('方式3结果:', response?.rows?.length || 0, '条记录')
        } catch (error) {
          console.log('方式3失败:', error.message)
        }
      }
      
      console.log('最终API响应:', response)
      console.log('响应数据结构:', response ? Object.keys(response) : '无响应')
      
      // 检查响应状态
      if (!response) {
        throw new Error('API调用失败，无响应')
      }
      
      if (response.success === false) {
        throw new Error(`API调用失败: ${response.error_code || '未知错误'}`)
      }
      
      // 处理响应数据
      let actualRows = []
      if (response.rows) {
        actualRows = response.rows
        console.log('找到数据在 response.rows')
      } else if (response.data && response.data.rows) {
        actualRows = response.data.rows
        console.log('找到数据在 response.data.rows')
      } else if (response.data && Array.isArray(response.data)) {
        actualRows = response.data
        console.log('找到数据在 response.data (数组格式)')
      }
      
      console.log('原始容器数据数量:', actualRows.length)
      
      if (actualRows.length === 0) {
        console.warn('⚠️ 警告：容器管理表中没有找到任何数据')
        console.log('可能的原因:')
        console.log('1. 当前用户没有查看该表的权限')
        console.log('2. 表中确实没有数据')
        console.log('3. API调用参数不正确')
        console.log('4. 需要特殊的视图ID或筛选条件')
        
        return {
          ...response,
          rows: [],
          warning: '未找到容器数据，可能是权限或数据可见性问题'
        }
      }
      
      // 转换和筛选容器数据
      const processedContainers = actualRows
        .map((row, index) => {
          const container = {
            id: row.rowid || '',
            containerCode: row[CONTAINER_FIELDS.CONTAINER_CODE] || '',
            status: row[CONTAINER_FIELDS.STATUS] || '',
            deliveryStation: row[CONTAINER_FIELDS.DELIVERY_STATION] || '',
            rawData: row
          }
          
          // 调试前几条记录
          if (index < 3) {
            console.log(`容器记录 ${index + 1}:`, {
              id: container.id,
              containerCode: container.containerCode,
              status: container.status,
              deliveryStation: container.deliveryStation,
              statusType: typeof container.status
            })
          }
          
          return container
        })
      
      // 筛选可用容器（排除状态为"使用完成"的容器，筛选配送站点）
      const availableContainers = processedContainers.filter(container => {
        // 确保有容器码
        if (!container.containerCode || !container.containerCode.trim()) {
          console.log('过滤掉无容器码的记录:', container.id)
          return false
        }
        
        // 检查状态（只允许"待使用"状态的容器）
        const status = (container.status || '').toString().trim()
        
        // 只允许"待使用"状态的容器
        const isAvailableForUse = status === '待使用' || 
                                 status === 'pending' || 
                                 status === 'available' ||
                                 status === '可用'
        
        if (!isAvailableForUse) {
          console.log('过滤掉非待使用状态的容器:', {
            containerCode: container.containerCode, 
            status: status,
            reason: '状态不是待使用'
          })
          return false
        } else {
          console.log('✅ 允许的容器状态:', {
            containerCode: container.containerCode,
            status: status,
            reason: '状态为待使用'
          })
        }
        
        // 配送站点筛选逻辑
        if (orderDeliveryStation && orderDeliveryStation.trim()) {
          const containerDeliveryStation = (container.deliveryStation || '').toString().trim()
          
          // 容器的配送站点为空或与订单的配送站点相同
          const isStationMatch = containerDeliveryStation === '' || 
                                containerDeliveryStation === orderDeliveryStation.trim()
          
          if (!isStationMatch) {
            console.log('过滤掉配送站点不匹配的容器:', {
              containerCode: container.containerCode,
              containerStation: containerDeliveryStation,
              orderStation: orderDeliveryStation.trim(),
              reason: '配送站点不匹配'
            })
            return false
          } else {
            console.log('配送站点匹配的容器:', {
              containerCode: container.containerCode,
              containerStation: containerDeliveryStation || '(空)',
              orderStation: orderDeliveryStation.trim(),
              matched: true
            })
          }
        }
        
        return true
      })
      
      console.log('处理后的可用容器数量:', availableContainers.length)
      console.log('可用容器列表:')
      availableContainers.forEach((container, index) => {
        console.log(`  ${index + 1}. 容器码: ${container.containerCode}, 状态: ${container.status}, 配送站点: ${container.deliveryStation || '(空)'}`)
      })
      
      // 筛选统计信息
      console.log('=== 筛选统计 ===')
      console.log(`原始容器数量: ${actualRows.length}`)
      console.log(`处理后容器数量: ${processedContainers.length}`)
      console.log(`最终可用容器数量: ${availableContainers.length}`)
      console.log('筛选条件:')
      console.log('  - 状态必须为: 待使用/pending/available/可用')
      console.log('  - 必须有有效的容器码')
      if (orderDeliveryStation) {
        console.log(`  - 配送站点为 "${orderDeliveryStation}" 或为空`)
      } else {
        console.log('  - 无配送站点限制')
      }
      
      return {
        ...response,
        rows: availableContainers,
        total: availableContainers.length,
        originalTotal: actualRows.length
      }
      
    } catch (error) {
      console.error('获取容器数据失败:', error)
      console.error('错误详情:', error.stack)
      throw error
    }
  }

  // 测试容器管理表连接
  async testContainerConnection() {
    try {
      console.log('=== 容器管理表连接测试 ===')
      console.log('容器管理表工作表ID:', WORKSHEET_IDS.CONTAINER_MANAGEMENT)
      
      // 测试基础连接 - 尝试多种参数组合
      console.log('尝试方式1: 标准API调用')
      let response = await http.post('/getFilterRows', {
        appKey: this.appKey,
        sign: this.sign,
        worksheetId: WORKSHEET_IDS.CONTAINER_MANAGEMENT,
        notGetTotal: false,
        pageSize: 50,
        pageIndex: 1
      })
      
      console.log('方式1响应:', response)
      
      // 如果没有数据，尝试不带分页参数
      if (!response.rows || response.rows.length === 0) {
        console.log('尝试方式2: 不带分页参数')
        response = await http.post('/getFilterRows', {
          appKey: this.appKey,
          sign: this.sign,
          worksheetId: WORKSHEET_IDS.CONTAINER_MANAGEMENT
        })
        console.log('方式2响应:', response)
      }
      
      // 如果还没有数据，尝试使用视图ID
      if (!response.rows || response.rows.length === 0) {
        console.log('尝试方式3: 使用视图ID')
        response = await http.post('/getFilterRows', {
          appKey: this.appKey,
          sign: this.sign,
          worksheetId: WORKSHEET_IDS.CONTAINER_MANAGEMENT,
          viewId: '',  // 使用默认视图
          pageSize: 100,
          pageIndex: 1
        })
        console.log('方式3响应:', response)
      }
      
      console.log('容器管理表连接测试响应:', response)
      
      if (response && response.success === true) {
        console.log('✅ 容器管理表连接成功')
        console.log('数据总数:', response.total)
        console.log('当前页数据量:', response.rows?.length || 0)
        
        if (response.rows && response.rows.length > 0) {
          console.log('第一条记录示例:', response.rows[0])
          console.log('可用字段:', Object.keys(response.rows[0]))
          
          // 检查配置的字段ID是否存在
          const firstRow = response.rows[0]
          console.log('=== 字段ID验证 ===')
          console.log(`容器码字段(${CONTAINER_FIELDS.CONTAINER_CODE}):`, firstRow[CONTAINER_FIELDS.CONTAINER_CODE])
          console.log(`容器状态字段(${CONTAINER_FIELDS.STATUS}):`, firstRow[CONTAINER_FIELDS.STATUS])
          
          // 显示所有记录的状态值，了解状态的具体格式
          console.log('=== 所有容器的状态值 ===')
          response.rows.forEach((row, index) => {
            console.log(`容器 ${index + 1} - 容器码:`, row[CONTAINER_FIELDS.CONTAINER_CODE], '状态:', row[CONTAINER_FIELDS.STATUS])
          })
          
          // 分析所有字段，重点找容器相关信息
          console.log('=== 容器字段分析 ===')
          const allFields = Object.keys(firstRow)
          console.log('字段总数:', allFields.length)
          
          // 只显示可能包含容器信息的字段
          const containerLikeFields = []
          const statusLikeFields = []
          
          allFields.forEach(fieldId => {
            const value = firstRow[fieldId]
            if (value && typeof value === 'string') {
              const valueLower = value.toLowerCase()
              // 查找可能的容器码字段
              if (valueLower.includes('container') || valueLower.includes('容器') || 
                  value.match(/^[A-Z0-9\-]{3,20}$/)) {
                containerLikeFields.push({ fieldId, value })
              }
              // 查找可能的状态字段  
              if (valueLower.includes('状态') || valueLower.includes('status') ||
                  valueLower.includes('使用') || valueLower.includes('完成') ||
                  valueLower.includes('可用') || valueLower.includes('available')) {
                statusLikeFields.push({ fieldId, value })
              }
            }
          })
          
          console.log('可能的容器码字段:', containerLikeFields)
          console.log('可能的状态字段:', statusLikeFields)
          
          // 显示所有字段ID（分批显示，避免截断）
          console.log('所有字段ID (前10个):', allFields.slice(0, 10))
          console.log('所有字段ID (11-20个):', allFields.slice(10, 20))
          if (allFields.length > 20) {
            console.log('所有字段ID (剩余):', allFields.slice(20))
          }
        }
      } else {
        console.log('❌ 容器管理表连接失败:', response)
      }
      
      return response
    } catch (error) {
      console.error('❌ 容器管理表连接测试失败:', error)
      return { success: false, error: error.message }
    }
  }
}

const wmsApi = new WMSApiService()
export default wmsApi